package controllers

import (
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	"main/src/models"
	"main/src/utils"
)

func AddUserHandler(c *fiber.Ctx) error {
	var newUser models.User
	db := c.Locals("db").(*gorm.DB)
	if err := c.BodyParser(&newUser); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid request"})
	}

	if err := utils.GetUser(db, &newUser, &models.User{}); err == nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "User with this username already exists"})
	}

	err := utils.AddUser(db, &newUser)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to add user"})
	}

	var addedUser models.User
	utils.GetUser(db, &newUser, &addedUser)

	return c.JSON(fiber.Map{"message": "User added successfully", "user": addedUser})
}
